package com.wang.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: along
 * @Create: 2021/4/25
 * @Description:递增顺序搜索树
 */
public class Solution897 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    //使用一个数组来存放遍历的结果
    public TreeNode increasingBST1(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();//一个数组来存放二叉搜索树中序遍历得结果
        inOrder(root, res);
        TreeNode dummyNode = new TreeNode(-1);
        TreeNode cur = dummyNode;
        //把数组中的的所有元素都追加到它前一个节点的右树上
        for (int value : res) {
            cur.right = new TreeNode(value);
            cur = cur.right;
        }
        return dummyNode.right;
    }
    //中序遍历递归
    public void inOrder(TreeNode root, List<Integer> res) {
        if (root == null) return;
        inOrder(root.left, res);
        res.add(root.val);
        inOrder(root.right, res);
    }

    //在遍历的过程中修改，不使用额外数组
    public TreeNode resNode;
        public TreeNode increasingBST2(TreeNode root) {

            TreeNode dummyNode = new TreeNode(-1);
            resNode = dummyNode;
            inorder(root);
            return dummyNode.right;
        }

        public void inorder(TreeNode node) {
            if (node == null) {
                return;
            }
            inorder(node.left);

            // 在中序遍历的过程中修改节点指向
            resNode.right = node;//把dummyNode的右指针指向当前的node
            node.left = null;//把node左指针置空
            resNode = node;

            inorder(node.right);
        }

}
